<?php
  	require_once('../utils/logged_in.php');
	require_once('../utils/query.php');

	$tradeID = $_POST["tradeID"];

	$who = execute_query("SELECT userid1 FROM Trade WHERE tradeid='%s'", $tradeID);
	$who = mysql_result($who, 0);
	if($who==$drupaluid)
	{
		execute_query("UPDATE Trade SET user1accepted=1 WHERE tradeid='%s'", $tradeID);
	}
	else
	{
		execute_query("UPDATE Trade SET user2accepted=1 WHERE tradeid='%s'", $tradeID);
	}

	$result = execute_query("SELECT user1accepted, user2accepted FROM Trade WHERE tradeid='%s'", $tradeID);
	$result = mysql_fetch_array($result);

	if($result[0]==1 && $result[1]==1)
	{
		$user1 = $drupaluid;
		$user2 = execute_query("SELECT userid2 FROM Trade WHERE tradeid='%s'", $tradeID);
		$user2 = mysql_result($user2, 0);

		//Get all of the possession IDs of cards that are part of the trade
		$posIDs = execute_query("SELECT possessionid FROM TradePossession WHERE tradeid='%s'", $tradeID);
		
		while($row = mysql_fetch_array($posIDs))
		{
			$owner = execute_query("SELECT userid FROM Possession WHERE possessionid='%s'", $row[0]);
			$owner = mysql_result($owner, 0);
			if($owner==$user1)
			{
				execute_query("UPDATE Possession SET userid='%s' WHERE possessionid='%s'", $user2, $row[0]);
			}
			else
			{
				execute_query("UPDATE Possession SET userid='%s' WHERE possessionid='%s'", $user1, $row[0]);
			}			
		}
		
		execute_query("DELETE FROM Trade WHERE tradeid='%s'", $tradeID);
		execute_query("DELETE FROM TradePossession WHERE tradeid='%s'", $tradeID);
		
		echo "Trade Completed";
	}
	else
	{
		echo "Trade Accepted. Other user must agree to the trade now.";
	}
	

?>